var supplierObj = [];
var limit = 15;
var tid;
var orgObj = convertOrgToObj(orgList);
var storageObj = convertEnumToObj(storageList);
layui.use(['laypage', 'table', 'form', 'laydate'], function(){
    var table = layui.table;
    var form = layui.form,laydate = layui.laydate;

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'orgId', title: '公司', width:100, align: 'center',templet:function (val) {
                return orgObj[val.orgId];
            }}
            ,{field: 'storageName', title: 'ERP仓位名称', width: 160,align: 'center',templet: function (val) {
                if (isNull(val.storageName)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.storageName + '</div>';
            }}
            ,{field: 'controlStorage', title: '工控仓位名称', width: 160, align: 'center',templet: function (val) {
                if (isNull(val.controlStorage)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.controlStorage + '</div>';
            }}
            ,{field: 'materialName', title: '材料名称', width: 180, align: 'center',templet: function (val) {
                if (isNull(val.materialName)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.materialName + '</div>';
            }}
            ,{field: 'lineCode', title: '生产线编号', width: 160, align: 'center',templet: function (val) {
                if (isNull(val.lineCode)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.lineCode + '</div>';
            }}
            ,{field: 'lineName', title: '生产线名称', width: 160, align: 'center',templet: function (val) {
                if (isNull(val.lineName)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.lineName + '</div>';
            }}
            ,{field: 'status', title: '状态', width:80, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '备注', width: 220, align: 'center'}
            ,{field: 'creator', title: '创建人', width: 100, align: 'center'}
            ,{field: 'createTime', title: '创建时间', width: 120, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 120, align:'center', templet:function (val) {
                var str = '<a lay-event="detail" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-primary">详情</a>';
                if (isUpdate == 1)
                    str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                if (val.status == 0){
                //     str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">禁用</a>';
                //     str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                }else{
                    // str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">启用</a>';
                }
                return str;
            }}
        ]
    ];

    laydate.render({
        elem: '#add-takeTime',
        theme: 'molv',
        type: 'datetime',
        format: 'yyyy-MM-dd HH:mm:ss'
    });

    laydate.render({
        elem: '#update-takeTime',
        theme: 'molv',
        type: 'datetime',
        format: 'yyyy-MM-dd HH:mm:ss'
    });

    table.render({
        elem: '#body-list'
        ,url: '/system/storage/match/page'
        ,method: 'post'
        ,page: true
        ,contentType: 'application/json'
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit,
            orgId:$('.search-origin').val(),
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res);
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要禁用？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option =  '{"id": '+id+', "status":'+updateStatus+'}';
                save(option, "/system/storage/match/updatestatus");
            }, function(index){
            });
        } else if(layEvent === 'edit'){
            if (isUpdate == 0) {
                layer.msg('您没有修改权限~！');
                return ;
            }
            tid = data.id;
            console.log(tid)
            $("#updateTitle").text("修改工控仓位对应关系");
            $('#update-mainDiscount-body').show();
            $(".update-search-origin").val(data.orgId);
            loadMaterialList({orgId: data.orgId, materialId: data.materialId});
            loadGetstorageList({orgId: data.orgId,lineId:data.lineId,storageId: data.storageId});
            loadControlStorageList({orgId: data.orgId,lineId:data.lineId,controlId: data.controlId});
            loadLineList({orgId: data.orgId,lineId: data.lineId});
            $(".update-remark").val(data.remark);
            $("#updateBtn").show();
            form.render();
        } else  if(layEvent === 'detail'){
            $("#updateTitle").text("查询工控仓位对应关系");
            $('#update-mainDiscount-body').show();
            $(".update-search-origin").val(data.orgId);
            loadMaterialList({orgId: data.orgId, materialId: data.materialId});
            loadGetstorageList({orgId: data.orgId,storageId: data.storageId});
            loadControlStorageList({orgId: data.orgId,controlId: data.controlId});
            loadLineList({orgId: data.orgId,lineId: data.lineId});
            $(".update-remark").val(data.remark);
            $("#updateBtn").hide();
            form.render();
        }
    });

    form.on('select(search-status)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-origin)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-line)', function(data) {
        $(".btn-query").trigger("click");
    });

    $('.btn-query').on('click', function () {//搜索按钮
        var searchVal = $('.search-text').val();
        var status = $('.search-status').val();
        var orgId = $('.search-origin').val();
        var lineId = $('.search-line').val();

        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (!isNull(status))
            option['status'] = status;
        if (!isNull(lineId))
            option['lineId'] = lineId;
        table.reload('body-list', {
            where: option
        });
    });

    $("#update-mainDiscount-body .close").on("click", function() {
        $("#update-mainDiscount-body").hide();
        $("#update-mainDiscount-body-body input").val("");
        $("#update-mainDiscount-body select").val("");
        $("#update-mainDiscount-body textarea").val("");
        $(".qrcode-show").hide();
        form.render();
        tid = -1;
    });

    form.on('submit(updateBtns)', function() {
        if (isUpdate == 0) {
            layer.msg('您没有修改权限~！');
            return ;
        }
        var option = null;
        var orgId = $(".update-search-origin").val();
        var storageId = $(".update-storage").val();
        var materialId = $(".update-material").val();
        var controlId = $(".update-control").val();
        var controlStorage = $(".update-control").find('option:selected').attr('data-name');
        var lineId = $(".update-line").val();
        var remark = $(".update-remark").val();
        var erpStorageType = $(".update-storage").find('option:selected').attr('data-storageType');
        var controlStorageType = $(".update-control").find('option:selected').attr('data-storageType');
        var takeTime = $('.update-takeTime').val();
        if (isNull(takeTime)) {
            layer.msg('盘存时间不能为空~！');
            return;
        }
        if (erpStorageType != controlStorageType) {
            layer.msg('ERP仓位类型与工控仓位类型不符[筒仓对应筒仓、堆场对应堆场]~!');
            return ;
        }
        option  = '{"id":'+tid+' ,"orgId":'+orgId+', "storageId":'+storageId+', "materialId":'+materialId +
        ', "controlId":'+controlId+',"controlStorage":"'+controlStorage+'","lineId":'+lineId
        +', "remark":"'+remark+'","takeTime":"' + takeTime + '"}'
        console.log(option)
        if (isNull(tid) || tid == -1) {
            layer.msg("获取修改信息错误,请刷新再试！");
            return ;
        }
        save(option, "/system/storage/match/update");
    });

    //新增页面选择类型
    form.on('select(add-search-origin)', function(data) {
        var orgId = data.value;
        var lineId = $(".add-line").val();
        // loadMaterialList({orgId: orgId});
        // loadLineList({orgId: orgId});
        loadGetstorageList({orgId: orgId, lineId:lineId});
        loadControlStorageList({orgId: orgId, lineId:lineId});
    });
    form.on('select(add-line)', function(data) {
        var orgId = $(".add-search-origin").val();
        var lineId = data.value;
        loadGetstorageList({orgId: orgId, lineId:lineId});
        loadControlStorageList({orgId: orgId, lineId:lineId});
    });
    form.on('select(add-storage)', function(data) {
        var orgId = $(".add-search-origin").val();
        var storageType = $(".add-storage").find('option:selected').attr('data-storageType');
        var materialId = $(".add-storage").find('option:selected').attr('data-materialId');
        console.log(storageType)
        loadMaterialList({orgId: orgId, storageType:storageType,materialId:materialId});
    });
    form.on('select(update-storage)', function(data) {
        var orgId = $(".update-search-origin").val();
        var storageType = $(".update-storage").find('option:selected').attr('data-storageType');
        var materialId = $(".update-storage").find('option:selected').attr('data-materialId');
        loadMaterialList({orgId: orgId, storageType:storageType,materialId:materialId});
    });
    form.on('select(update-search-origin)', function(data) {
        var orgId = data.value;
        var lineId = $(".update-line").val();
        // loadMaterialList({orgId: orgId});
        // loadLineList({orgId: orgId});
        loadGetstorageList({orgId: orgId, lineId:lineId});
        loadControlStorageList({orgId: orgId, lineId:lineId});
    });
    form.on('select(update-line)', function(data) {
        var orgId = $(".update-search-origin").val();
        var lineId = data.value;
        loadGetstorageList({orgId: orgId, lineId:lineId});
        loadControlStorageList({orgId: orgId, lineId:lineId});
    });

    //打开新增页面
    $('.btn-add').on('click', function () {//新增流程
        if (isInsert == 0) {
            layer.msg('您没有新增权限~！');
            return ;
        }
        $('.addModal').show();
        $(".add-weight-show").show();
        $(".add-rate-show").hide();
        var orgId = $(".add-search-origin").val();
        var lineId = $(".add-line").val();
        // loadMaterialList({orgId: orgId});
        loadGetstorageList({orgId: orgId, lineId:lineId});
        loadControlStorageList({orgId: orgId, lineId:lineId});
        // loadLineList({orgId: orgId});
    });

    //关闭新增页面
    $(".addModal .close").on("click", function () {//关闭新增流程窗口
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        form.render();
    });

    //新增
    form.on('submit(addBtns)', function () {
        if (isInsert == 0) {
            layer.msg('您没有新增权限~！');
            return ;
        }
        var option = null;
        var orgId = $(".add-search-origin").val();
        var storageId = $(".add-storage").val();
        var materialId = $(".add-material").val();
        var controlId = $(".add-control").val();
        var controlStorage = $(".add-control").find('option:selected').attr('data-name');
        var lineId = $(".add-line").val();
        var remark = $(".add-remark").val();
        var erpStorageType = $(".add-storage").find('option:selected').attr('data-storageType');
        var controlStorageType = $(".add-control").find('option:selected').attr('data-storageType');
        var takeTime = $('.add-takeTime').val();
        if (erpStorageType != controlStorageType) {
            layer.msg('ERP仓位类型与工控仓位类型不符[筒仓对应筒仓、堆场对应堆场]~!');
            return ;
        }
        option  = '{"orgId":'+orgId+', "storageId":'+storageId+', "materialId":'+materialId+', "controlId":'+controlId
            +',"controlStorage":"'+controlStorage+'","lineId":'+lineId+', "remark":"'+remark+'","takeTime":"' + takeTime + '"}';
        save(option,"/system/storage/match/save");
    });

    function save(option, url) {//新增或修改
        var loading = layer.load(1);
        console.log(option);
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            data: option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg(res.msg);
                    $(".btn-query").trigger("click");
                    $("#update-mainDiscount-body").hide();
                    $("#update-mainDiscount-body input").val("");
                    $("#update-mainDiscount-body select").val("");
                    $("#update-mainDiscount-body textarea").val("");
                    $("#add-mainDiscount-body").hide();
                    $("#add-mainDiscount-body input").val("");
                    $("#add-mainDiscount-body select").val("");
                    $("#add-mainDiscount-body textarea").val("");
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    //根据公司标识查询材料表
    function loadMaterialList(obj) {
        var loading = layer.load(1);
        $.ajax({
            url: '/system/storage/match/getMainMaterial',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            success: function (res) {
                layer.close(loading);
                console.log(res)
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择材料</option>';
                    $.each(data, function (i, v) {
                        var nameNorms = v.nameNorms;
                        var storeType = '';
                        if (v.storeType != null && v.storeType > -1) {
                            storeType = '[' + storageObj[v.storeType] + ']';
                            html += '<option value="' + v.materialId + '">' + nameNorms + storeType + '</option>';
                        }
                    });
                    $('.add-material').html(html);
                    $('.update-material').html(html);
                } else {
                    $('.add-material').html('<option value="">暂无数据</option>');
                    $('.update-material').html('<option value="">暂无数据</option>');
                }
                if (!isNull(obj.materialId)) {
                    $('.add-material').val(obj.materialId);
                    $('.update-material').val(obj.materialId);
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    //根据公司标识查询erp仓位表
    function loadGetstorageList(obj) {
        var loading = layer.load(1);
        $.ajax({
            url: '/system/storage/match/getstorage',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            success: function (res) {
                console.log(res)
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择ERP仓位</option>';
                    $.each(data, function (i, v) {
                        var storageType = '';
                        var name = v.name;
                        if (v.type != null)
                            storageType = '[' + storageObj[v.type] + ']';
                        html += '<option value="' + v.id + '" data-name="' + v.name + '" data-materialId="' + v.materialId
                            + '" data-storageType="' + v.type + '">' + name + storageType + '</option>';
                    });
                    $('.add-storage').html(html);
                    $('.update-storage').html(html);
                } else {
                    $('.add-storage').html('<option value="">暂无数据</option>');
                    $('.update-storage').html('<option value="">暂无数据</option>');
                }
                if (!isNull(obj.storageId)) {
                    $('.update-storage').val(obj.storageId);
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }


    //根据公司标识查询工控
    function loadControlStorageList(obj) {
        var loading = layer.load(1);
        $.ajax({
            url: '/system/storage/match/getControlStorage',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            success: function (res) {
                layer.close(loading);
                console.log(res)
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择工控仓位</option>';
                    $.each(data, function (i, v) {
                        var storageType = '';
                        if (v.type != null)
                            storageType = '[' + storageObj[v.type] + ']';
                        html += '<option value="' + v.id + '" data-name="' + v.name + '" data-storageType="' + v.type + '">' + v.name + storageType + '</option>';
                    });
                    $('.add-control').html(html);
                    $('.update-control').html(html);
                } else {
                    $('.add-control').html('<option value="">暂无数据</option>');
                    $('.update-control').html('<option value="">暂无数据</option>');
                }
                if (!isNull(obj.controlId)) {
                    $('.update-control').val(obj.controlId);
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }


    //根据公司标识查询生产线数据
    function loadLineList(obj) {
        var loading = layer.load(1);
        $.ajax({
            url: '/system/storage/match/getLine',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择erp仓位</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.id + '">' + v.name + '</option>';
                    });
                    $('.add-line').html(html);
                    $('.update-line').html(html);
                } else {
                    $('.add-line').html('<option value="">暂无数据</option>');
                    $('.update-line').html('<option value="">暂无数据</option>');
                }
                if (!isNull(obj.lineId)) {
                    $('.update-line').val(obj.lineId);
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            $(".btn-query").trigger("click");
        }
    });
});